<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from 'vue';

import 'highlight.js/styles/stackoverflow-light.css'
import 'highlight.js/lib/common';
import hljs from "highlight.js";

import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const editMode = ref(true);

//定义指令，自动使用highlight.js渲染所有<pre><dode>代码块
const vHigelight = {
  mounted(el :any) {
    let blocks = el.querySelectorAll('pre code');
    blocks.forEach((block: HTMLElement)=>{
      block.setAttribute('style', 'margin-top: 8px;');
      hljs.highlightBlock(block)
    })
  }
}

const editorRef = shallowRef();
const valueHtml = ref('');

const toolbarConfig = {
  excludeKeys: []
}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<template>
  <div v-if="!editMode">
    <button @click="editMode = true">编辑</button>
    <div v-higelight v-html="valueHtml"></div>
  </div>
  
  <div v-if="editMode">
    <button @click="editMode = false">保存</button>
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" 
      :defaultConfig="toolbarConfig" mode="default"/>
    <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml"
      :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated"/>
  </div>
</template>
